package com.gitee.shigen.lucene.controller;

import com.gitee.shigen.common.msg.Result;
import com.gitee.shigen.lucene.service.LuceneService;
import com.gitee.shigen.lucene.vo.Content;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author shigenfu
 */
@RestController
@RequestMapping("/index")
public class ContentController {

    @Resource
    private LuceneService luceneService;

    @GetMapping("/search")
    public ResponseEntity<List<Content>> search(
        @RequestParam(required = false) String keyword,
        @RequestParam(defaultValue = "1") int page,
        @RequestParam(defaultValue = "10") int pageSize
    ) {
        try {
            String[] fields = {"title", "description"};
            List<Content> contentList = luceneService.search(fields, keyword, page, pageSize);
            return ResponseEntity.ok(contentList);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PostMapping(value = "/add")
    public Result<Long> createContent(@RequestBody List<Content> contentList) {
        Long count = luceneService.save(contentList);
        return Result.success(count);
    }

    @DeleteMapping(value = "/index/{id}")
    public Result deleteById(@PathVariable("id") String id) {
        luceneService.deleteById(id);
        return Result.success(null);
    }

    @GetMapping(value = "/index/{id}")
    public Result<Content> queryById(@PathVariable("id") String id) {
        Content content = luceneService.getDocumentById(id);
        return Result.success(content);
    }

    @GetMapping(value = "getFakeData")
    public Result<List<Content>> getFakeData(@RequestParam(value = "count", defaultValue = "10", required = false) Integer count) {
        List<Content> data = luceneService.getFakeData(count);
        return Result.success(data);
    }

}
